<!--
 * @Description: vue拖拽位置交换
 * @Author: your name
 * @Date: 2023-05-23
 * @LastEditTime: 2023-05-23
 * @LastEditors: Please set LastEditors
-->
<template>
  <transition-group tag="div" class="page container">
    <div
      class="item"
      v-for="item in items"
      :key="item.key"
      :style="{ 'background-color': item.color, border: '1px solid' }"
      draggable
      @dragstart="handleDragStart($event, item)"
      @dragover.prevent="handleDragOver($event, item)"
      @dragenter="handleDragEnter($event, item)"
      @dragend="handleDragEnd($event, item)"
    >
      <span>{{ item }}</span>
    </div>
  </transition-group>
</template>

<script>
export default {
  name: 'ToolBar',
  data() {
    return {
      items: [
        { key: 1, color: '#3883a0' },
        { key: 2, color: '#4883a0' },
        { key: 3, color: '#5883a0' },
        { key: 4, color: '#6883a0' },
        { key: 5, color: '#7883a0' },
        { key: 6, color: '#8883a0' },
        { key: 7, color: '#9883a0' }
      ],
      ending: null,
      dragging: null
    }
  },
  methods: {
    handleDragStart(e, item) {
      console.log(e, item, '===handleDragStart')
      this.dragging = item
    },
    handleDragEnd(e, item) {
      console.log(e, item, '===handleDragEnd')
      if (this.ending.key === this.dragging.key) {
        return
      }
      let newItems = [...this.items]
      const src = newItems.indexOf(this.dragging),
        dst = newItems.indexOf(this.ending)
      newItems.splice(src, 1, ...newItems.splice(dst, 1, newItems[src]))
      console.log(newItems)

      this.items = newItems
      this.$nextTick(() => {
        this.dragging = null
        this.ending = null
      })
    },
    handleDragOver(e) {
      console.log(e, '===handleDragOver')
      // 首先把div变成可以放置的元素，即重写dragenter/dragover
      // 在dragenter中针对放置目标来设置
      e.dataTransfer.dropEffect = 'move'
    },
    handleDragEnter(e, item) {
      console.log(e, item, '===handleDragEnter')
      // 为需要移动的元素设置dragstart事件
      e.dataTransfer.effectAllowed = 'move'
      this.ending = item
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}
.item {
  width: 200px;
  height: 200px;
  margin: 10px;
  color: $--color-white;
  transition: all  0.3s linear;
}
</style>
